/// @Classname : HcTextButtonPanel
/// @Author :
/// @Time : 2024-04-01 14:12
/// @Description : //todo

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:hc_ui/config/hc_customer_config.dart';
import 'package:hc_ui/widget/button/hc_text_button.dart';
import 'package:hc_ui/widget/grid/hc_grid.dart';

import '../../theme/hc_button_panel_theme.dart';

class HcTextButtonPanel extends StatefulWidget {
  //文字按钮的个数
  final List<String> buttonTextList;

  //点击的回调
  final Function(int)? buttonIndexCallback;

  //最大展示的个数
  final int maxShowCount;

  //分隔符的颜色
  final Color? dividerColor;

  //分隔符的宽度
  final double? dividerWidth;

  final Widget? expand;
  final Widget? collapse;
  final double? buttonWidth;
  final HcButtonPanelTheme? themeData;

  const HcTextButtonPanel(
      {Key? key,
      required this.buttonTextList,
      this.buttonIndexCallback,
      required this.maxShowCount,
      this.dividerColor,
      this.dividerWidth,
      this.expand,
      this.collapse,
      this.themeData,
      this.buttonWidth})
      : super(key: key);

  @override
  State<HcTextButtonPanel> createState() => _HcTextButtonPanelState();
}

class _HcTextButtonPanelState extends State<HcTextButtonPanel> {
  @override
  Widget build(BuildContext context) {
    HcButtonPanelTheme theme = widget.themeData ?? HcButtonPanelTheme();
    theme = HcCustomerConfig().allTheme.buttonPanelTheme.merge(theme);
    List<Widget> finalBtnList = List.empty(growable: true);
    bool needShowMore = widget.buttonTextList.length > widget.maxShowCount;
    List<String> showList = widget.buttonTextList.sublist(
        0,
        min(widget.buttonTextList.length,
            widget.maxShowCount + (needShowMore ? -1 : 0)));
    for (int i = 0; i < widget.maxShowCount; i++) {
      if (i < showList.length) {
        finalBtnList.add(
            HcTextButton(onPressed: () => _onBtnTap(i), text: showList[i]));
      } else if (needShowMore) {
        finalBtnList
            .add(HcTextButton(onPressed: () => _onBtnTap(i), text: "more"));
      } else {
        finalBtnList.add(const SizedBox.shrink());
      }
    }

    finalBtnList = finalBtnList.reversed.toList();
    return Container(
      padding: theme.padding,
      decoration: BoxDecoration(color: theme.backgroundColor),
      child: HcGrid(
        itemBuilder: (BuildContext context, int index) {
          return SizedBox(
              width: widget.buttonWidth ?? double.infinity,
              child: finalBtnList[index]);
        },
        crossAxisCount: widget.maxShowCount,
        itemCount: finalBtnList.length,
      ),
    );
  }

  void _onBtnTap(index) {
    if (widget.buttonIndexCallback != null) {
      widget.buttonIndexCallback!.call(index);
    }
  }
}
